import {getRecommendList} from "../service/ajax.js";
import {formatCreateTime,formatSongTime,songListFilter} from "../util/util.js";
import {reactive} from "../util/reactive.js";
import {initPlayerControl, PlayerCoverBackMode,playerListRender} from "../home/control.js";

const recommendDetail={
    playlst:[],
    detail:{},
    listActive:0, //歌单列表被选中歌曲的id
};

// 响应式数据：当数据改变时，执行歌单列表初始化函数
const activeProxy=reactive(
    {
    active:recommendDetail.listActive,
    },
    initList
)

// 双击播放音乐涉及到的变量，变量改变前面的播放标志也改变
const isPlayProxy=reactive(
    {
        active:recommendDetail.listActive,//存放音乐的id
        isPlay:false,//歌曲是否播放
    },
    initList
)

// 推荐页面渲染
export const recommendListPage=async({params=""})=>{
    // 清除所有定时器
    document.querySelector('#app').innerHTML=`加载中`;
    const result=await getRecommendList(params);
    if(result.code==404){
        document.querySelector('#app').innerHTML`未找到`;
    }else{
        recommendDetail.detail=result.playlist;
        initDescribe();
        recommendDetail.playlist=result.playlist.tracks;
        initList();
        initEvent();
    }
    const musicId=window.localStorage.getItem("musicId");
    window.localStorage.setItem("lastRecommendId",params);
    PlayerCoverBackMode("player",musicId);
}
//推荐歌单描述初始化
function initDescribe(){
    let tagsTemplate="";
    recommendDetail.detail.tags.forEach((tag,index)=>{
        index==recommendDetail.detail.tags.length-1
        ?(tagsTemplate+=`<span class="tag>${tag} </span>`)
        :(tagsTemplate+=`<span class="tag">${tag}/ </span>`);

    })
    let time =formatCreateTime(recommendDetail.detail.createTime);//格式化时间
    document.querySelector('#app').innerHTML=`
     <div class="w">
                <!-- 推荐页 -->
                <div class="recommend-header">
                    <a href="#home">首页</a>/
                    <span>推荐歌单页</span>
                </div>
                <div class="recommend-wrapper">
                    <!-- 歌单介绍 -->
                    <div class="recommend-describe d-flex justify-content-start">
                        <div class="recommend-describe-left">
                            <img src="${recommendDetail.detail.coverImgUrl}" alt="">
                        </div>
                        <div class="recommend-describe-right d-flex flex-column align-items-start">
                            <h4 class="recommend-describe-right-title single-text-omitted">
                                ${recommendDetail.detail.name}
                            </h4>
                            <div class="recommend-describe-right-creator d-flex">
                                <img src="" class="avatar" alt="">
                                <div class="creator">${recommendDetail.detail.creator.detailDescription}</div>
                                <div class="create-time">${time}</div>
                            </div>
                            <div class="recommend-describe-right-add d-flex">
                                <span class="btn">播放全部</span>
                                <span class="add">+</span>
                            </div>
                            <div class="recommend-describe-right-info">
                                <div class="info">
                                    <span class="label">标签：</span>
                                    ${tagsTemplate}
                                </div>
                                <div class="info">
                                    <span class="label">歌曲：</span>
                                    <span class="label-info">${recommendDetail.detail.trackCount}</span>
                                    <span class="label">播放：</span>
                                    <span class="label-info">${recommendDetail.detail.playCount}</span>
                                </div>
                                <div class="info">
                                    <span class="label">简介：</span>
                                    <span class="label-info">${recommendDetail.detail.description}</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 歌单列表 -->
                    <div class="recommend-list">
                        <h4 class="recommend-list-title">歌曲列表</h4>
                        <!-- 表格头部 -->
                         <ul class="recommend-list-songlist-header d-flex justify-sontent-start">
                            <li class="songlist-header-name">歌曲</li>
                            <li class="songlist-header-author">歌手</li>
                            <li class="songlist-header-album">专辑</li>
                            <li class="songlist-header-time">时长</li>
                         </ul>

                        <!-- 表格内容 -->
                         <ul class="recommend-list-songlist-body">
                            
                         </ul>
                    </div>
                </div>


            </div>
    `
}
//歌单初始化
function initList(){
    const listDom=document.getElementsByClassName("recommend-list-songlist-body")[0];
    let listTemplate="";
    let isEvenOrOdd="";
    recommendDetail.playlist.forEach((item,index)=>{
        isEvenOrOdd=index%2==0?"even":"odd";
        listTemplate+=`
        <li class="songlist-item ${isEvenOrOdd} ${activeProxy.active==item.id? "active":""} d-flex justify-content-start" data-index=${item.id}>
                <div class="songlist-number font-color">
                    <span class="index">${index+1}</span>
                    <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-shoucang"></use>
                    </svg>
                    <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-xiazai"></use>
                    </svg>
                </div>
                <div class="songlist-songname">
                ${item.name}
                </div>
                <div class="songlist-artist font-color">
                ${item.ar[0].name}
                </div>
                <div class="songlist-album font-color">
                ${item.al.name}
                </div>
                <div class="songlist-time font-color">
                    ${Math.floor(item.dt/1000/60)}:${Math.round(((item.dt/1000)%60))}
                </div>
            </li>
        `
    });
    listDom.innerHTML=listTemplate;
}


function initEvent(){
    const songListWrap=document.querySelector(".recommend-list-songlist-body");
    songListWrap.addEventListener("mouseenter",(e)=>{
        const targetname=e.target.nodeName.toLocaleLowerCase();
        if(targetname =="li"){
            const id=e.target.getAttribute("data-index");
            if(activeProxy.active==id) return;//防止多次触发
            activeProxy.active=id;
        }
    },true)

    // 双击播放音乐
    songListWrap.addEventListener("dblclick",
        async (e)=>{
            // 修改列表的播放图标
            console.log(123);
            const targetName=e.target.nodeName.toLocaleLowerCase();
            if(targetName=="li"){
                const id=e.target.getAttribute("data-index");
                isPlayProxy.active=id;
                window.localStorage.setItem("musicId",id);
            }else if(targetName=="div"){
                const id=e.target.parentNode.getAttribute("data-index");
                isPlayProxy.active=id;
                window.localStorage.setItem("musicId",id);
            }
            isPlayProxy.isPlay=true;
            initPlayerControl();
        },true
    )

    // 点击将歌曲劣币哦啊添加到播放列表中
    const addSongList=document.querySelector(".recommend-describe-right-add");
    addSongList.addEventListener("click",
        (e)=>{
            // 添加不重复的歌曲列表
            const arr=songListFilter(recommendDetail.playlist);
            console.log(arr);
            // 将数组加入到localStorage中
            window.localStorage.setItem("songList",JSON.stringify(arr));
            // 动态生成播放列表
            playerListRender();
    })
}






